package com.example.toolproject.demo.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.toolproject.demo.domain.DataSearch;
import com.example.toolproject.demo.domain.User;
import com.example.toolproject.demo.service.DataSearchService;
import com.example.toolproject.demo.util.ResultBean;
import com.example.toolproject.demo.util.excel.ExcelUtils;
import com.example.toolproject.demo.util.jwt.JwtUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.print.attribute.IntegerSyntax;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName DataSeacherController
 * @Description TODO
 * @Author lvyongwei
 * @Date 2020-06-19 13:56
 **/
@Controller
@CrossOrigin
@RequestMapping("/dataSearch")
public class DataSeacherController {

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private DataSearchService dataSearchService;

    /**
     * 下载导入模板
     * @param request
     * @param response
     */
    @GetMapping("/getImportTemplate")
    public void importTemplate(HttpServletRequest request, HttpServletResponse response){
        excelUtils.cooperation(request,response, DataSearch.class,"导入信息");
    }

    /**
     * 数据导入  (未修改，修改了service和domain)
     * 2020-09-08 11:14  新加功能，保证普通学生导入数据不能真正导入到数据库
     *     解决：正常导入,加入用户id和角色id,在固定时间定时删除或者退出删除
     * @return
     */
    @PostMapping("/import")
    @ResponseBody
    public ResultBean importData(@RequestParam("file") MultipartFile file,HttpServletRequest request){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        long len = file.getSize();
        double fileSize = 0;
        //判断长度是否小于0
        if (fileSize > len) {
            return ResultBean.error("导入失败，请传入文件");
        }
        //判断文件大小是否超过10M
        boolean flag=checkFileSizeIsLimit(len,10,"M");
        if(flag==false){
            return ResultBean.error("导入文件超过10M");
        }
        //执行excel工具读取，获取要导入的对象集合
        List<Object> lists=excelUtils.upload(file,DataSearch.class);
        if(lists.size()==0){
            return ResultBean.error("表中没有数据，请添加正确的数据");
        }
        return dataSearchService.imports(lists,u);
    }


    /**
     * 根据type查找数据信息
     * @param request
     * @param type
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getAllDataSearch")
    @ResponseBody
    public ResultBean getAllDataSearch(HttpServletRequest request,int type,Integer pageNum,Integer pageSize){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        if( pageNum==null || pageNum==0){
            pageNum=1;
        }
        if(pageSize==null || pageSize==0){
            pageSize=10;
        }
        if(type==0){
            return ResultBean.error("没有选择类型");
        }
        /**
         * 获取用户id
         */
        int userId=u.getId();
        //执行分页
        PageHelper.startPage(pageNum,pageSize);
        //根据type获取数据信息
        List<DataSearch> dataSearches=dataSearchService.selectAllDataSearch(type,userId);
        //获取分页信息
        PageInfo<DataSearch> pageInfo=new PageInfo<DataSearch>(dataSearches);
        return ResultBean.success("成功获取数据信息",pageInfo);
    }

    /**
     * 判断文件大小是否超过一定范围
     * @param fileLen
     * @param fileSize
     * @param fileUnit
     * @return
     */
    public static boolean checkFileSizeIsLimit(Long fileLen, int fileSize, String fileUnit) {
        double fileSizeCom = 0;
        if ("B".equals(fileUnit.toUpperCase())) {
            fileSizeCom = (double) fileLen;
        } else if ("K".equals(fileUnit.toUpperCase())) {
            fileSizeCom = (double) fileLen / 1024;
        } else if ("M".equals(fileUnit.toUpperCase())) {
            fileSizeCom = (double) fileLen / (1024*1024);
        } else if ("G".equals(fileUnit.toUpperCase())) {
            fileSizeCom = (double) fileLen / (1024*1024*1024);
        }
        System.out.println(fileSizeCom);
        if (fileSizeCom > fileSize) {
            return false;
        }
        return true;
    }


    /**
     * 根据数据分类以及搜索条件查询数据信息
     * @param request
     * @param type     数据类型
     * @param pageNum  当前页码
     * @param pageSize 每页显示条数
     * @param message  搜索的内容
     * @return
     */
    @GetMapping("/getAllDataSearchByMessage")
    @ResponseBody
    public ResultBean getAllDataSearchByMessage(HttpServletRequest request,int type,Integer pageNum,Integer pageSize,String message){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        if(StringUtils.isEmpty(pageNum) || pageNum==0){
            pageNum=1;
        }
        if(StringUtils.isEmpty(pageSize) || pageSize==0){
            pageSize=10;
        }
        if(type==0 || message==null){
            return ResultBean.error("请选择类型，并输入想要查找的数据");
        }
        /**
         * 获取用户id
         */
        int userId=u.getId();
        //执行分页
        PageHelper.startPage(pageNum,pageSize);
        //根据type获取数据信息
        List<DataSearch> dataSearches=dataSearchService.selectAllDataSearchByMessage(type,message,userId);
        //获取分页信息
        PageInfo<DataSearch> pageInfo=new PageInfo<DataSearch>(dataSearches);
        return ResultBean.success("成功获取数据信息",pageInfo);
    }


    /**
     * 根据数据id查询数据详情信息
     * @param request
     * @return
     */
    @GetMapping("/getDataSearchById")
    @ResponseBody
    public ResultBean getDataSearchById(HttpServletRequest request,int dataSearchId){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        DataSearch dataSearch=dataSearchService.getDataSearchById(dataSearchId);
        if(StringUtils.isEmpty(dataSearch) || dataSearch==null){
            return ResultBean.error("未查询到数据内容");
        }
        return ResultBean.success("查询到数据信息",dataSearch);
    }


    /**
     * 获取自己引用的文化资源数据
     * @param request
     * @return
     */
    @GetMapping("/getSelfAllDataSearch")
    @ResponseBody
    public ResultBean getSelfAllDataSearch(HttpServletRequest request){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        /**
         * 获取到userId
         */
        int userId=u.getId();
        try{
            //执行查找方法
            List<DataSearch> list=dataSearchService.getSelfAllDataSearch(userId);
            return ResultBean.success("获取文化资源成功",list);
        }catch (Exception e){
            return ResultBean.error("获取文化资源失败");
        }
    }
}
